package chz.learning;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Login extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		Cookie[] cookies = req.getCookies();
		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("user")) {
				writer.println("user=" + cookie.getValue());
			}
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		login(req, resp);
	}

	public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String ck_user = "";
		String user = request.getParameter("user");
		String password = request.getParameter("password");
		HttpSession session = request.getSession();

		Cookie[] cookies = request.getCookies();

		for (Cookie cookie : cookies) {
			if (cookie.getName().equals("user")) {
				ck_user = cookie.getValue();
			}
		}
		if ("" != ck_user) {
			request.getSession().invalidate();
			if (user.equals(ck_user)) {
				System.out.println("还是原来的用户");
			} else {
				response.getWriter().println("current posted user:" + user);
			}
		} else {
			Cookie cookie = new Cookie("user", user);
			cookie.setMaxAge(1800);
			response.addCookie(cookie);

			session.setAttribute("password", password);
		}
	}

}
